/**
 *
 */
package com.angel.io.descriptor;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;

import com.angel.common.helpers.FileHelper;
import com.angel.io.exceptions.InvalidFileAccessException;
import com.angel.io.fileInformation.ExportFileInformation;
import com.angel.webapp.file.FileInformation;

/**
 * @author William
 *
 */
public class ExportedFileDescriptor {

	private Date beginProcess;
	private Date endProcess;
	private File file;
	private Integer rows;

	public ExportedFileDescriptor(){
		super();
	}

	public ExportedFileDescriptor(Date beginProcess){
		super();
		this.beginProcess = beginProcess;
	}

	/**
	 * @return the file
	 */
	public File getFile() {
		return file;
	}

	/**
	 * @param file the file to set
	 */
	public void setFile(File file) {
		this.file = file;
	}

	/**
	 * @return the rows
	 */
	public Integer getRows() {
		return rows;
	}

	/**
	 * @param rows the rows to set
	 */
	public void setRows(Integer rows) {
		this.rows = rows;
	}

	/**
	 * @return the beginProcess
	 */
	public Date getBeginProcess() {
		return beginProcess;
	}

	/**
	 * @param beginProcess the beginProcess to set
	 */
	public void setBeginProcess(Date beginProcess) {
		this.beginProcess = beginProcess;
	}

	/**
	 * @return the endProcess
	 */
	public Date getEndProcess() {
		return endProcess;
	}

	/**
	 * @param endProcess the endProcess to set
	 */
	public void setEndProcess(Date endProcess) {
		this.endProcess = endProcess;
	}

	public Long calculateDuration(){
		return this.getEndProcess().getTime() - this.getBeginProcess().getTime();
	}

	public FileInformation buildFileInformation(){
		InputStream inputStream = null;
		try {
			inputStream = FileHelper.findInputStreamFor(this.getFile().getAbsolutePath());
		} catch (FileNotFoundException e) {
			//TODO Verify directory at server.
			throw new InvalidFileAccessException("Cannot access to file at [" + this.getFile().getAbsolutePath() + "].", e);
		}
		FileInformation fileInformation = new ExportFileInformation(
				"text/plain",
				this.getFile().getName(),
				inputStream,
				Integer.valueOf(String.valueOf(this.getFile().length()))
				);
		
		return fileInformation;
	}
}
